import { Component, OnInit } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { OtcCustomerService } from '@core/routes-services/otc-customer.service';
import { CenterService } from '@core/routes-services/center.service';
import { myValidNull } from '@core/util/string-utils';

@Component({
  selector: 'app-otc-cus-area',
  templateUrl: './otc-cus-area.component.html',
})
export class OtcCusAreaComponent implements OnInit {
  entity: any = {};
  validateForm: FormGroup;
  isLoading: boolean = true;

  allCenters:any [] = []

  selectedOptions:any [] = [];
  centerOptions:any [] = [];

  constructor(private fb: FormBuilder,
              private modal: NzModalRef,
              private otcCustomerService: OtcCustomerService,
              private centerService: CenterService,
              public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.initAllCenters();
    this.initValidateForm();
  }

  /**
   * 初始化获取所有运营中心
   */
  initAllCenters(){
    this.centerService.getAll().then((res) => {
      console.log(res )
      if (res.status.toString().startsWith("20")) {
        this.allCenters = res.data;
        this.selectedOptions = this.allCenters.filter((center) => center.customerId == this.entity.id);
        this.centerOptions  = this.allCenters.filter((center) => center.customerId == null);
        this.initValidateForm();
      } else {
        this.message.warning(res.message);
      }
      this.isLoading = false;
    }, error => {
      this.message.error(error.message ? error.message : error.error)
      this.isLoading = false;
    });
  }

  initValidateForm() {
    let centerIds = []
    if(!myValidNull(this.selectedOptions) && this.selectedOptions.length > 0){
      centerIds = this.selectedOptions.map(c => c.id)
    }
    this.validateForm = this.fb.group({
      name: [this.entity.name, [Validators.required, Validators.maxLength(30)]],
      selectedIds: [centerIds, []],
      centerIds: [[], []],
    });
  }
  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      this.isLoading = true;
      // console.log(this.validateForm.value);
      this.otcCustomerService.setCenter(this.entity.id, this.validateForm.value).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.modal.close(true);
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });

    }
  }

  close() {
    this.modal.destroy();
  }
}
